package priv.dajie.tzzq.spider.dota.c5;

import org.apache.http.client.methods.HttpGet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import priv.dajie.tzzq.BaseStatic;
import priv.dajie.tzzq.spider.model.SpiderInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class C5Infos extends BaseStatic {

    private static Logger logger = LogManager.getLogger(C5Infos.class.getName());

    public static SpiderInfo getC5Info() {
        logger.debug("获取c5信息");
        HttpGet httpGet = new HttpGet("https://www.c5game.com/dota.html");
        String html = open(httpGet);
        Document document = Jsoup.parse(html);
        Map<String, String> heroCN = getHeros(document);
        Map<String, String> rarityCN = getRarity(document);
        Map<String, String> typeCN = getType(document);
        return new SpiderInfo(heroCN, rarityCN, typeCN);
    }

    private static Map<String, String> getHeros(Document document) {
        Map<String, String> heroCN = new HashMap<>();
        Elements heroDivs = document.select("div.filter-hero");
        for (Element div : heroDivs) {
            Pattern pattern = Pattern.compile("hero=(.*)&");
            String heroHref = div.select("a").first().attr("href");
            String heroName = div.select("img").first().attr("alt");
            Matcher matcher = pattern.matcher(heroHref);
            if (matcher.find()) {
                String hero = matcher.group(1);
                heroCN.put(hero, heroName);
            }
        }
        return heroCN;
    }

    private static Map<String, String> getRarity(Document document) {
        Map<String, String> rarityCN = new HashMap<>();
        Elements raritys = document.select("a[class*=rarity]");
        Pattern pattern = Pattern.compile("rarity=(.*)&");
        return getStringStringMap(rarityCN, raritys, pattern);
    }

    private static Map<String, String> getStringStringMap(Map<String, String> map, Elements elements, Pattern pattern) {
        for (Element element : elements) {
            String href = element.attr("href");
            Matcher matcher = pattern.matcher(href);
            if (matcher.find()) {
                map.put(matcher.group(1), element.text());
            }
        }
        return map;
    }

    private static Map<String, String> getType(Document document) {
        Map<String, String> typeCN = new HashMap<>();
        Elements divs = document.select("div.filter-cat-content-right");
        Element div = divs.get(4);
        Elements as = div.select("a");
        Pattern pattern = Pattern.compile("type=(.*)&");
        getStringStringMap(typeCN, as, pattern);
        typeCN.remove("taunt");
        typeCN.remove("wearable");
        typeCN.remove("bundle");
        return typeCN;
    }
}
